<template>
  <view>
    <!--单张图片上传-->
    <u-upload
			:fileList="fileList"
			:width="width"
			:height="height"
			:uploadText="uploadText"
			:maxCount="maxCount"
			accept="image"
      @afterRead="afterRead"
			@delete="deletePic"
		>
    </u-upload>

    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
  import {
    baseUrl
  } from '@/common/config'

  export default {
    props: {
      width: { // 内部预览图片区域和选择图片按钮的区域宽度，单位rpx，不能是百分比，或者auto
        type: Number,
        default: 80
      },
      height: { // 内部预览图片区域和选择图片按钮的区域高度，单位rpx，不能是百分比，或者auto
        type: Number,
        default: 80
      },
      uploadText: { // 上传区域的提示文字
        type: String,
        default: ''
      },
      previewUrl: { // 预览图地址
        type: Array
      },
      maxCount: { //上传个数限制
        type: Number,
        default: 1
      },
			showSuccessToast: {	// 是否需要上传成功后的吐司提示
				type: Boolean,
				default: true
			}
    },
    data() {
      return {
        accept: ['jpg', 'jpeg', 'png'],
        fileList: []
      };
    },
    mounted() {
      
    },
    watch: {
      previewUrl: {
        handler(val) {
          if (val.length === 0 ) {
            this.fileList = []
          } else {
            this.fileList = [] //情况后添加
            val.forEach((item, index) => {
			  if(item){
				this.fileList.push({
				  url:item
				})  
			  }	
            })
          }
        },
		immediate: true,
		deep: true
      }
    },
    methods: {
      // 删除图片
      deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1)
        this.$emit('deleteImg', event.index) 
      },
      // 新增图片
      async afterRead(event) {
        let url = event.file.url.split('.')
        if (!this.accept.includes(url[1].toLowerCase())) {
          this.$refs.uToast.show({
            message: '上传图片格式错误',
            type: 'error'
          })
          return
        }

        // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
        let lists = [].concat(event.file)
        let fileListLen = this[`fileList${event.name}`].length
        lists.map((item) => {
          this[`fileList${event.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url)
          let item = this[`fileList${event.name}`][fileListLen]
          this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: result
          }))
          fileListLen++
          this.$emit('handleImg', result)
        }
      },
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: `${baseUrl}/user-center/app-file/upload-file`,
            filePath: url,
			name: 'file', // 固定
            formData: {
              user: 'test'
            },
            header: {
              'Authorization': 'Bearer ' + uni.getStorageSync('access_token'),
              'content-type': 'multipart/form-data' 
            },
            success: (res) => {
              let result = JSON.parse(res.data)
              resolve(result.datas)
							
							if(this.showSuccessToast){
								this.$refs.uToast.show({
								  message: '操作成功',
								  type: 'default',
								})
							}

            },
            fail: () => {
              this.$refs.uToast.show({
                message: '操作失败',
                type: 'error'
              })
            }
          });
        })
      },

    }
  }
</script>